package SpringDemo.IOC.com.junjie.framework.beans.factory.xml;

import SpringDemo.IOC.com.junjie.framework.beans.BeanDefinition;
import SpringDemo.IOC.com.junjie.framework.beans.MutablePropertyValues;
import SpringDemo.IOC.com.junjie.framework.beans.PropertyValue;
import SpringDemo.IOC.com.junjie.framework.beans.factory.support.BeanDefinitionReader;
import SpringDemo.IOC.com.junjie.framework.beans.factory.support.BeanDefinitionRegistry;
import SpringDemo.IOC.com.junjie.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * XML格式的Bean定义读取器实现类
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    //声明Bean定义注册表
    private final BeanDefinitionRegistry beanDefinitionRegistry;

    public XmlBeanDefinitionReader() {
        this.beanDefinitionRegistry = new SimpleBeanDefinitionRegistry();
    }

    /**
     * 构造函数
     * @param beanDefinitionRegistry Bean定义注册表
     */
    public XmlBeanDefinitionReader(BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    @Override
    public BeanDefinitionRegistry getBeanDefinitionRegistry() {
        return beanDefinitionRegistry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //解析XML文件，将Bean定义加载到注册表中
        //1. 加载XML文件
        SAXReader saxReader = new SAXReader();
        InputStream is = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document document = saxReader.read(is);
        //2. 解析XML文件，将Bean定义加载到注册表中
        List<Element> bean = document.getRootElement().elements("bean");
        for (Element element : bean) {
            //读取Bean标签的属性
            String id = element.attributeValue("id");
            String className = element.attributeValue("class");

            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);

            //创建属性值集合对象
            MutablePropertyValues propertyValues = new MutablePropertyValues();

            //读取Bean标签的子标签，将属性值加载到Bean定义中
            List<Element> property = element.elements("property");
            for (Element element1 : property) {
                String name = element1.attributeValue("name");
                String ref = element1.attributeValue("ref");
                String value = element1.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);

                //添加到属性值集合中
                propertyValues.addPropertyValue(propertyValue);
            }

            //将属性值集合设置到Bean定义中
            beanDefinition.setPropertyValues(propertyValues);

            //将Bean定义注册到注册表中
            beanDefinitionRegistry.registry(id, beanDefinition);
        }
    }
}
